#!/bin/bash

# 获取所有僵尸进程的PPID（状态以Z开头），排除init进程(PPID=1)，并去重
zombie_ppids=$(ps -A -o stat,ppid | awk '$1 ~ /^Z/ && $2 != 1 {print $2}' | sort -u)

if [ -z "$zombie_ppids" ]; then
    echo "没有发现僵尸进程"
    exit 0
fi

echo "发现僵尸进程的父进程ID: $zombie_ppids"

# 先尝试SIGTERM(15)优雅终止
for ppid in $zombie_ppids; do
    kill -15 $ppid 2>/dev/null && echo "已向PPID $ppid 发送SIGTERM"
done

sleep 3  # 等待父进程处理僵尸进程

# 检查剩余的僵尸进程
remaining_ppids=$(ps -A -o stat,ppid | awk '$1 ~ /^Z/ && $2 != 1 {print $2}' | sort -u)

if [ -n "$remaining_ppids" ]; then
    echo "仍有未清理的僵尸进程，父进程ID: $remaining_ppids"
    # 强制终止剩余的父进程
    for ppid in $remaining_ppids; do
        kill -9 $ppid 2>/dev/null && echo "已向PPID $ppid 发送SIGKILL"
    done
else
    echo "所有僵尸进程已成功清理"
fi